package com.flute.haflute.jobbox.base.storage;

import java.util.Properties;
import java.util.WeakHashMap;

import com.flute.haflute.tools.ClusterUtils;

public class StorageServiceFactory {
	public static final String DEFAULT_STORAGE = "USE_CONFIGURED_CASSANDRA_STORAGE_SERVICE_FACTORY";

	/** 根据不同TableName，或者说Cassandra的ColumnFamily */
	private static WeakHashMap<String, StorageServicePool> pools = new WeakHashMap<String, StorageServicePool>();

	/**
	 * Default factory method
	 * 
	 * @return 不支持区间查询的默认数据库服务
	 * @throws Exception
	 */
	public static synchronized KeyValueStorageService getStorageService()
			throws Exception {
		return getStorageService(false);
	}

	/**
	 * Default factory method with range selection
	 * 
	 * @param supportRangeQuery
	 *            是否请求支持区间查询的数据库，true：支持，false：不支持
	 * @return KeyValueStorageService，如果supportRangeQuery为true，返回支持区间查询的数据库服务，
	 *         否则不支持区间查询的默认数据库服务。
	 * @throws Exception
	 */
	public static synchronized KeyValueStorageService getStorageService(
			boolean supportRangeQuery) throws Exception {
		if (supportRangeQuery) {
			return getStorageService("CrawlerTime2UniqueURL");
		} else {
			return getStorageService(DEFAULT_STORAGE);
		}
	}

	/**
	 * 通用存储服务
	 * 
	 * @param tableName
	 *            表名，如果是Cassandra，则相当于ColumnFamily。
	 * @return KeyValueStorageService，根据tableName返回的数据库服务。
	 * @throws Exception
	 */
	public static synchronized KeyValueStorageService getStorageService(
			String tableName) throws Exception {
		StorageServicePool pool = pools.get(tableName);
		if (pool == null) {
			pool = newServicePool(tableName);
			pools.put(tableName, pool);
		}
		return pool.borrowService();
	}

	public static synchronized void release(
			KeyValueStorageService storageService) {
		StorageServicePool pool = pools.get(storageService.serviceType());
		if (pool == null) {
			pool = pools.get(DEFAULT_STORAGE);
		}

		if (pool != null) {
			pool.releaseService(storageService);
		}
	}

	/**
	 * 目前只是新生成Cassandra的数据库服务。
	 * 
	 * @param tableName
	 * @return
	 * @throws Exception
	 */
	private static StorageServicePool newServicePool(String tableName)
			throws Exception {
		Properties props = new Properties(
				ClusterUtils.get3rdPartConfiguration());
		if (!DEFAULT_STORAGE.equals(tableName)) {
			props.setProperty("cassandra.Keyspace.ColumnFamily", tableName);
		}
		return new CassandraStorageServicePool(props);
	}

}
